package com.amap.rideroute.util;

import android.util.Log;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.rideroute.bean.AddressPointBean;

import java.util.ArrayList;
import java.util.List;

/**
 * 点距离排序
 */
public class SortPathUtil {
    /**
     * 对点进行距离排序,返回两两需要绘制距离的点数组的集合
     * @return
     */
    public static List<AddressPointBean> sortStraightPath(LatLonPoint currentLocation,List<AddressPointBean> points){
        //计算当前用户与集合中点的距离，找出最短距离
        List<AddressPointBean> resultPoints = new ArrayList<>();
        getShortDistancePointArgs(currentLocation,points,resultPoints);
        Log.e("集合",resultPoints.toString());
        return resultPoints;
    }
    private static void getShortDistancePointArgs(LatLonPoint flagPoint,List<AddressPointBean> points,List<AddressPointBean> resultPoints){
        LatLonPoint[] shortPointArgs = new LatLonPoint[2];
        AddressPointBean shortAddress = null;
        float distance = -1;
        LatLng latLngStart = new LatLng(flagPoint.getLatitude(),flagPoint.getLongitude());
        LatLng latLngEnd;

        //先看看有没有需要置顶的点
        boolean isHaveShowTop = false;
        for (AddressPointBean addressPointBean : points) {
            if(addressPointBean.isShowTop()){
                isHaveShowTop = true;
                shortAddress = addressPointBean;
                break;
            }
        }
        //没有置顶的点就按常规排序
        if(!isHaveShowTop){
            for (AddressPointBean addressPointBean : points) {
                LatLonPoint point = addressPointBean.getCurrentPoint();
                latLngEnd = new LatLng(point.getLatitude(),point.getLongitude());
                float tempDistance = AMapUtils.calculateLineDistance(latLngStart, latLngEnd);
                //找出最短的距离
                if(distance == -1){
                    distance = tempDistance;
                    shortAddress = addressPointBean;
                    Log.e("最短距离A",tempDistance + "");
                }else if(tempDistance < distance){
                    distance = tempDistance;
                    shortAddress = addressPointBean;
                    Log.e("最短距离B",tempDistance + "");
                }
                Log.e("最短距离",tempDistance + "");
            }
        }

        shortPointArgs[0] = flagPoint;
        shortPointArgs[1] = shortAddress.getCurrentPoint();
        AddressPointBean addressPointBean = new AddressPointBean();
        addressPointBean.setLatLonPoints(shortPointArgs);
        addressPointBean.setAddressName(shortAddress.getAddressName());
        addressPointBean.setShowTop(false);
        addressPointBean.setCurrentPoint(shortAddress.getCurrentPoint());
        resultPoints.add(addressPointBean);
        points.remove(shortAddress);
        if(points.size() > 0){
            getShortDistancePointArgs(shortAddress.getCurrentPoint(),points,resultPoints);
        }
    }
}
